package com.levy.contronller.javaWeb.findImageTest;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.levy.utils.Base64Utils;
import com.levy.utils.FileTool.TextFileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;


/**
 * Created by levy on 2018/11/5.
 */
public class AliFormOcrUtils {

    private static final String HOST = "https://form.market.alicloudapi.com";
    private static final String PATH = "/api/predict/ocr_table_parse";
    private static final String APPCODE = "1e3b403c005e43e3a64c070bf6b03366";

    /*
     * 获取参数的json对象
     */
    public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }


    public static String getConvertResult(String imgFile, String format) throws Exception {
        String result = "";
        //如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        Boolean is_old_format = false;
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("format", format);
        configObj.put("finance", false);
        configObj.put("dir_assure", false);
        String config_str = configObj.toString();

        String method = "POST";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APPCODE);

        Map<String, String> querys = new HashMap<String, String>();

        // 对图像进行base64编码
        String imgBase64 = Base64Utils.encodeBase64File(imgFile);
        System.out.println("---" + imgBase64);

        // 拼装请求body的json字符串
        String bodys = getRequestBody(is_old_format, config_str, imgBase64);
        System.out.println("request param : " + bodys);

        //发起请求
        HttpResponse response = HttpUtils.doPost(HOST, PATH, method, headers, querys, bodys);
        int stat = response.getStatusLine().getStatusCode();
        if (stat != 200) {
            System.out.println("Http code: " + stat);
            System.out.println("http header error msg: " + response.getFirstHeader("X-Ca-Error-Message"));
            System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
            return null;
        }

        String res = EntityUtils.toString(response.getEntity());
        JSONObject res_obj = JSON.parseObject(res);
        if (is_old_format) {
            JSONArray outputArray = res_obj.getJSONArray("outputs");
            String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
            JSONObject out = JSON.parseObject(output);
            System.out.println(out.toJSONString());

        } else {
            result = res_obj.getString("tables");
            System.out.println("--最终返回的参数--" + result);
        }
        return result;
    }


    private static String getRequestBody(Boolean is_old_format, String config_str, String imgBase64) {
        JSONObject requestObj = new JSONObject();
        try {
            if (is_old_format) {
                JSONObject obj = new JSONObject();
                obj.put("image", getParam(50, imgBase64));
                if (config_str.length() > 0) {
                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            } else {
                requestObj.put("image", imgBase64);
                if (config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return requestObj.toString();
    }


    @Test
    public void test() {

        long l = System.currentTimeMillis();
        String imgFile = "C:\\Users\\levy\\Desktop\\1\\";
        String saveFile = "C:\\Users\\levy\\Desktop\\1\\q.xlsx";
        String type = "xlsx";
        try {
            String data = getConvertResult(imgFile, type);
            if ("xlsx".equals(type)) {
                Base64Utils.decoderBase64File(data, saveFile);
            } else {
                TextFileUtils.write(saveFile, data, "utf-8");
            }
            Thread.sleep(500);
            System.out.println("over");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println((System.currentTimeMillis() - l) / 1000);


    }


    @Test
    public void test2() {

        long l = System.currentTimeMillis();
        String imgFile = "C:\\Users\\levy\\Desktop\\1\\q.png";
        String saveFile = "C:\\Users\\levy\\Desktop\\1\\q.xlsx";
        String type = "xlsx";
        try {
            String data = getConvertResult(imgFile, type);
            if ("xlsx".equals(type)) {
                Base64Utils.decoderBase64File(data, saveFile);
            } else {
                TextFileUtils.write(saveFile, data, "utf-8");
            }
            Thread.sleep(500);
            System.out.println("over");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println((System.currentTimeMillis() - l) / 1000);


    }


    public static void main(String[] args) throws Exception {
        long l = System.currentTimeMillis();
        String imgFileDir = "G://pdf/small//";
        String saveFileDir = "G://pdf/html//ALI//";
        List<String> fileNames = FileUtil.listFileNames(imgFileDir);
        for (String s : fileNames) {
            String pdfbox_image_ = s.replaceAll("pdfbox_image_", "").replaceAll(".png", "");
            int i = Integer.parseInt(pdfbox_image_);
            String imgFile = imgFileDir + s;
            String fileNameWithOutSuff = s.substring(0, s.indexOf(".png")) + ".html";
            String saveFile = "";
            if (i > 52 && i < 59) {
                saveFile = saveFileDir + "//firstTable//" + fileNameWithOutSuff;
            } else if (i > 58) {
                saveFile = saveFileDir + "//secondTable//" + fileNameWithOutSuff;
            } else {
                continue;
            }

            String type = "html";
            try {
                Thread.sleep(5000);
                String data = getConvertResult(imgFile, type);
                if ("xlsx".equals(type)) {
                    Base64Utils.decoderBase64File(data, saveFile);
                } else {
                    TextFileUtils.write(saveFile, data, "utf-8");
                }
                System.out.println("over");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println((System.currentTimeMillis() - l) / 1000);

    }
}
